package com.hnkywl.sts.service.cwgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.cwgl.CgrkDao;
import com.hnkywl.sts.dao.cwgl.KmdmDao;
import com.hnkywl.sts.dao.cwgl.YwcbDao;
import com.hnkywl.sts.entity.cggl.Cgd;
import com.hnkywl.sts.entity.cggl.Jsd;
import com.hnkywl.sts.entity.cwgl.VoucherItemData;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.xsgl.Xsd;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-4-30
 * Time: 上午9:58
 * To change this template use File | Settings | File Templates.
 */
@Service
public class CgrkService {
    private CgrkDao cgrkDao;


    public String findAllCgrkList(String wzbm, String cgdh, Long dzckId, Date fhrqStart, Date fhrqEnd, String cglx, Long cggsId, Long cgbmId, Long cgrId, String zt, String sftzd, String htType, Long gysid, String rkzt, String zdr,Boolean dlkhcgd, int page, int rows) throws ParseException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        Page cgdPage = this.cgrkDao.findAllCgdList(null, wzbm, cgdh, dzckId, fhrqStart, fhrqEnd, cglx, cggsId, cgbmId, cgrId, zt, sftzd, htType, gysid, rkzt, zdr,dlkhcgd, page, rows);
        List<Map<String,Object>> cgdList = cgdPage.getResult();
        if(cgdList.size()>0){
            cgdList = getCzztByPj(cgdList);
        }
        String cgdmxJson = gson.toJson(cgdPage.getResult());
        return "{\"total\":" + cgdPage.getTotalCount() + ",\"rows\":" + cgdmxJson + "}";
    }

    public List<Map<String,Object>> getCzztByPj(List<Map<String,Object>> cgdList){
        for(Map<String,Object> x:cgdList){
            String czzt = "";
            if(Integer.parseInt(x.get("insertFlag").toString())==1 && Integer.parseInt(x.get("deleteFlag").toString())==1){
                czzt = "wdr";
            }else if(Integer.parseInt(x.get("insertFlag").toString())==1 && Integer.parseInt(x.get("deleteFlag").toString())==3){
                czzt = "sccg";
            }else if(Integer.parseInt(x.get("insertFlag").toString())==3 && Integer.parseInt(x.get("deleteFlag").toString())==1){
                czzt = "drcg";
            }else if(Integer.parseInt(x.get("insertFlag").toString())==2 && Integer.parseInt(x.get("deleteFlag").toString())==1 ||
                    Integer.parseInt(x.get("insertFlag").toString())==2 && Integer.parseInt(x.get("deleteFlag").toString())==3 ){
                czzt = "drsb";
            }else if(Integer.parseInt(x.get("insertFlag").toString())==3 && Integer.parseInt(x.get("deleteFlag").toString())==2){
                czzt = "scsb";
            }else{
                czzt = "null";
            }
            x.put("CZZT", czzt);
        }
        return cgdList;
    }

    @Transactional
    public Map getVoucherMaster(Long id, Integer attachment, String uuid, String year, String mouth, Yg yg) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        Cgd result = cgrkDao.get(id);
        voucherMaster.put("id", uuid);
        voucherMaster.put("vchrtypecode", "记");//凭证类别
        voucherMaster.put("acctyear", year != null ? year : "");//会计年度
        voucherMaster.put("acctperiod", mouth != null ? mouth : "");//会计期间
        voucherMaster.put("createdate", systemDate);//凭证日期
        voucherMaster.put("unitcode", result.getSbgs() != null && result.getSbgs().getJiuqiUnitCode() != null ? result.getSbgs().getJiuqiUnitCode() : "");//组织机构代码
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", yg.getXm());//制单人
        voucherMaster.put("attachment", attachment);//附件张数
        voucherMaster.put("memo", "");//备注
        voucherMaster.put("companyId", result.getSbgs().getId());//公司ID
        return voucherMaster;
    }

    //财务收付分录
    @Transactional
    public String findQtpzfl(Long id) {
        Cgd cgrk = this.cgrkDao.get(id);
        List<Map> list = this.cgrkDao.getVoucher(cgrk);
        List<Map> txcdJson = new ArrayList<Map>();
        for (int i =0;i<list.size() ;  i++){
            Map<String, Object> voucherItem = (Map<String, Object>)list.get(i);
            voucherItem.put("zy",voucherItem.get("digest"));
            voucherItem.put("km",voucherItem.get("subjectname"));
            voucherItem.put("jf",voucherItem.get("debit"));
            voucherItem.put("df",voucherItem.get("credit"));
            txcdJson.add(voucherItem);
        }
        return new Gson().toJson(txcdJson);
    }

    @Transactional
    public void cgrkChangeDrrq(Long cwsfId,Date date){
        Cgd x = this.cgrkDao.get(cwsfId);
        x.setDrrq(date);
        cgrkDao.save(x);
    }

    @Transactional
    public Map getU8VoucherItems(Long cgrkId, String uuid,List<VoucherItemData> voucherItemDataList,Date documentDate) {
        Cgd cgrk = this.cgrkDao.get(cgrkId);
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map> list = this.cgrkDao.getVoucher(cgrk);
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for(Map m : list){
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            voucherItem.put("entry_id", order);//分录编号
            voucherItem.put("account_code", m.get("subjectcode") != null ? m.get("subjectcode") : "");//科目代码
            voucherItem.put("natural_debit_currency", m.get("debit") != null ? df.format(m.get("debit")) : "0.00");//借方金额
            voucherItem.put("natural_credit_currency", m.get("credit")!= null ? df.format(m.get("credit")) : "0.00");//贷方金额
            voucherItem.put("unit_price", "0");//单价,在科目有数量核算时，填写此项
            voucherItem.put("debit_quantity", "0");//借方数量,在科目有数量核算时，填写此项
            voucherItem.put("credit_quantity", "0");//贷方数量,在科目有数量核算时，填写此项
            voucherItem.put("currency", "CNY");//货币代码
            voucherItem.put("exchange_rate2", "1.000000");//汇率
            voucherItem.put("settlement", "");//结算方式,在科目是银行或往来时，可以填写此项
            voucherItem.put("document_id", "");//票据号，在科目是银行或往来时，可以填写此项
            voucherItem.put("document_date",systemDate);//票据日期，在科目是银行或往来时，可以填写此项
            voucherItem.put("abstract", m.get("digest") != null ? m.get("digest") : "");//摘要
            Map<String, String> fzhsMap = new HashMap<String, String>();
            Map<String, String> xjllxmMap = new HashMap<String, String>();
            fzhsMap =  this.findFzhsByMap(m,fzhsMap);
            voucherItem.put("auxiliary_accounting", fzhsMap);
            voucherItem.put("cash_flow", xjllxmMap);
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }

    private Map<String,String > findFzhsByMap( Map<Object,String> map,Map<String, String> fzhsMap){
        if(map.get("customercode") !=null && !map.get("customercode").toString().equals("")){
            fzhsMap.put("cust_id",map.get("customercode"));
        }
        if(map.get("suppliercode") !=null && !map.get("suppliercode").toString().equals("")){
            fzhsMap.put("supplier_id",map.get("suppliercode"));
            fzhsMap.put("operator","-");
        }
        return fzhsMap;
    }

    @Transactional
    public Map getRevokeInfo(Long id) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        Cgd result = cgrkDao.get(id);
        if (result == null) {
            throw new RuntimeException("未获取凭证信息!");
        }
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MM");
        revokeInfo.put("id", result.getUuid());//凭证ID
        revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
        revokeInfo.put("unitcode", result.getCggs().getJiuqiUnitCode());//单位代码
        revokeInfo.put("vchrtypecode", "记");//会计年度
        revokeInfo.put("acctyear", result.getAcctyear());//会计年度
        revokeInfo.put("acctperiod",simpleDateFormat3.format(result.getDrrq()));//会计年度
        revokeInfo.put("vchrnum", result.getVoucherNum());//凭证号

        return revokeInfo;
    }


    @Autowired
    public void setCgrkDao(CgrkDao cgrkDao) {
        this.cgrkDao = cgrkDao;
    }

}
